<template>
  <div class="gateway-container">
    <!-- 网关选择和操作区域 -->
    <div class="operation-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="选择网关">
          <el-select v-model="selectedGatewayId" placeholder="请选择网关" style="width: 200px;" @change="handleGatewayChange">
            <el-option
              v-for="gateway in gatewayList"
              :key="gateway.id"
              :label="`${gateway.name} (${gateway.ip})`"
              :value="gateway.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备ESN">
          <el-input 
            v-model="searchForm.deviceESN" 
            placeholder="请输入设备ESN (例如: FF0100001111)"
            maxlength="12"
            @input="handleEsnInput"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :disabled="!selectedGatewayId">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd" :disabled="!selectedGatewayId">增加设备</el-button>
        <el-button type="success" @click="handleRefresh" :disabled="!selectedGatewayId">刷新列表</el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedDevices.length || !selectedGatewayId">
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 设备列表 -->
    <el-table
      v-loading="loading"
      :data="deviceList"
      @selection-change="handleSelectionChange"
      border
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="deviceId" label="设备编号" width="120" />
      <el-table-column prop="deviceESN" label="设备ESN" width="180" />
      <el-table-column prop="deviceStatus" label="状态">
        <template #default="{ row }">
          <el-tag :type="Number(row.deviceStatus) === 1 ? 'success' : 'danger'">
            {{ Number(row.deviceStatus) === 1 ? '在线' : '离线' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleView(row)">查看</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          <el-dropdown @command="(cmd: string) => handleDropdownCommand(cmd, row)" style="margin-left: 10px;">
            <el-button type="primary" link>
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="reboot">重启设备</el-dropdown-item>
                <el-dropdown-item command="version">查询版本</el-dropdown-item>
                <el-dropdown-item command="gain">增益调节</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="查看设备"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="deviceForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="设备编号" prop="deviceId">
          <el-input v-model="deviceForm.deviceId" placeholder="请输入设备编号" readonly />
        </el-form-item>
        <el-form-item label="设备ESN" prop="deviceESN">
          <el-input 
            v-model="deviceForm.deviceESN"
            placeholder="请输入设备ESN"
            readonly
          />
        </el-form-item>
        <el-form-item label="设备状态" prop="deviceStatus">
          <el-input :value="Number(deviceForm.deviceStatus) === 1 ? '在线' : '离线'" readonly />
        </el-form-item>
        <el-form-item label="设备类型">
          <el-input v-model="deviceType" placeholder="设备类型" readonly />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增设备对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增设备"
      width="500px"
      @close="cancelAdd"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="100px"
      >
        <el-form-item label="设备ID" prop="deviceId">
          <el-input-number v-model="addForm.deviceId" :min="1" placeholder="请输入设备ID" />
        </el-form-item>
        <el-form-item label="设备ESN" prop="deviceESN">
          <el-input 
            v-model="addForm.deviceESN"
            placeholder="请输入设备ESN (例如: FF0100001111)"
            maxlength="12"
            @input="addForm.deviceESN = addForm.deviceESN.toUpperCase()"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAdd">取消</el-button>
          <el-button type="primary" @click="submitAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 增益调节对话框 -->
    <el-dialog
      v-model="gainDialogVisible"
      title="增益调节"
      width="500px"
    >
      <el-form :model="gainForm" label-width="100px">
        <el-form-item label="当前设备ID">
          <el-input :value="gainForm.deviceId" readonly />
        </el-form-item>
        <el-form-item label="查询结果">
          <el-input :value="queriedGain" readonly placeholder="点击查询按钮获取" />
        </el-form-item>
        <el-form-item label="设置增益值">
          <el-input-number v-model="gainForm.gain" :min="1" :max="700" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="gainDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitQueryGain">查询</el-button>
          <el-button type="success" @click="submitSetGain">设置</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, reactive, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { gatewayStore } from '../../store/gateway';
import { storeToRefs } from 'pinia';
import { WebsocketIo } from '../../utils/websocket';

defineOptions({
  name: "Gateway"
})

// 网关相关
const gateway_store = gatewayStore();
const { gatewayList } = storeToRefs(gateway_store);
const selectedGatewayId = ref<number | null>(null);

// WebSocket相关
const ws = WebsocketIo.getInstance;
const wsStatus = ref(false);

// 设备列表相关
const deviceList = ref<any[]>([]);
const loading = ref(false);
const selectedDevices = ref<any[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索表单
const searchForm = reactive({
  deviceESN: ''
});

// 对话框相关
const dialogVisible = ref(false);
const addDialogVisible = ref(false);
const gainDialogVisible = ref(false);

// 表单数据
const deviceForm = reactive({
  deviceId: '',
  deviceESN: '',
  deviceStatus: ''
});

const addForm = reactive({
  deviceId: null,
  deviceESN: ''
});

const gainForm = reactive({
  deviceId: '',
  gain: null
});

const deviceType = ref('');
const queriedGain = ref('');

// 表单验证规则
const rules = {
  deviceId: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
  deviceESN: [{ required: true, message: '请输入设备ESN', trigger: 'blur' }]
};

const addRules = {
  deviceId: [{ required: true, message: '请输入设备ID', trigger: 'blur' }],
  deviceESN: [{ required: true, message: '请输入设备ESN', trigger: 'blur' }]
};

const formRef = ref();
const addFormRef = ref();

onMounted(async () => {
  await gateway_store.fetchGatewayList();
  if (gatewayList.value.length > 0) {
    selectedGatewayId.value = gatewayList.value[0].id;
    handleGatewayChange(selectedGatewayId.value);
  }
});

onUnmounted(() => {
  ws.removeMessageHandler(handleWsMessage, 'gateway_result');
});

// WebSocket消息处理
const handleWsMessage = (data: any) => {
  console.log('收到WebSocket消息:', data);
  
  if (data.action === 'gateway_result') {
    const { type, result, data: responseData } = data;
    
    if (result === 'success') {
      switch (type) {
        case 'queryAll':
          if (responseData) {
            deviceList.value = Array.isArray(responseData) ? responseData : [];
            total.value = deviceList.value.length;
            ElMessage.success(`设备列表刷新成功，共找到 ${total.value} 个设备`);
          } else {
            deviceList.value = [];
            total.value = 0;
            ElMessage.success('设备列表刷新成功，暂无设备');
          }
          break;
        case 'add':
          ElMessage.success(`设备添加成功: ID=${responseData?.id || addForm.deviceId}, ESN=${responseData?.esn || addForm.deviceESN}`);
          addDialogVisible.value = false;
          // 重置表单
          addForm.deviceId = null;
          addForm.deviceESN = '';
          // 刷新列表
          setTimeout(() => handleRefresh(), 500);
          break;
        case 'delete':
          ElMessage.success(`设备删除成功: ID=${responseData?.id || '已删除'}`);
          // 刷新列表
          setTimeout(() => handleRefresh(), 500);
          break;
        case 'queryDeviceType':
          deviceType.value = responseData?.deviceType || '未知类型';
          ElMessage.success(`设备类型查询成功: ${deviceType.value}`);
          break;
        case 'queryCircuitGain':
          queriedGain.value = responseData?.gain?.toString() || '未知';
          ElMessage.success(`电路增益查询成功: ${queriedGain.value}`);
          break;
        case 'setCircuitGain':
          ElMessage.success(`增益设置成功: ID=${responseData?.id || gainForm.deviceId}, 增益=${responseData?.gain || gainForm.gain}`);
          gainDialogVisible.value = false;
          // 重置表单
          gainForm.gain = null;
          queriedGain.value = '';
          break;
        case 'device_reboot':
          ElMessage.success(`设备重启成功: ID=${responseData?.id || '已重启'}`);
          break;
        case 'queryVersion':
          const version = responseData?.version || '未知版本';
          ElMessage.success(`设备版本查询成功: ${version}`);
          break;
        case 'queryGateway':
          ElMessage.success(`网关查询成功: ${JSON.stringify(responseData)}`);
          break;
        default:
          ElMessage.success(`操作成功: ${type}`);
      }
    } else {
      // 处理错误情况
      const errorMsg = responseData?.msg || responseData?.error || '操作失败';
      switch (type) {
        case 'queryAll':
          ElMessage.error(`设备列表查询失败: ${errorMsg}`);
          break;
        case 'add':
          ElMessage.error(`设备添加失败: ${errorMsg}`);
          break;
        case 'delete':
          ElMessage.error(`设备删除失败: ${errorMsg}`);
          break;
        case 'queryDeviceType':
          ElMessage.error(`设备类型查询失败: ${errorMsg}`);
          deviceType.value = '查询失败';
          break;
        case 'queryCircuitGain':
          ElMessage.error(`电路增益查询失败: ${errorMsg}`);
          queriedGain.value = '查询失败';
          break;
        case 'setCircuitGain':
          ElMessage.error(`增益设置失败: ${errorMsg}`);
          break;
        case 'device_reboot':
          ElMessage.error(`设备重启失败: ${errorMsg}`);
          break;
        case 'queryVersion':
          ElMessage.error(`版本查询失败: ${errorMsg}`);
          break;
        case 'queryGateway':
          ElMessage.error(`网关查询失败: ${errorMsg}`);
          break;
        default:
          ElMessage.error(`操作失败 [${type}]: ${errorMsg}`);
      }
    }
  }
};

// 网关切换处理
const handleGatewayChange = (gatewayId: number) => {
  const gateway = gatewayList.value.find(g => g.id === gatewayId);
  if (gateway) {
    const url = `ws://${gateway.ip}:8081`;
    ws.onOpen = () => {
      wsStatus.value = true;
      console.log(`与网关 ${gateway.name} (${gateway.ip}) 连接成功`);
    };
    ws.onClose = () => {
      wsStatus.value = false;
      console.log(`与网关 ${gateway.name} (${gateway.ip}) 连接断开`);
    };
    ws.onError = (err) => {
      wsStatus.value = false;
      console.error(`连接错误: ${err}`);
    };
    ws.connectWebsocket(url);
    ws.addMessageHandler(handleWsMessage, 'gateway_result');
    
    // 自动刷新设备列表
    handleRefresh();
  }
};

// 发送指令
const sendCommand = (payload: any) => {
  if (!ws.websocketIsNormal()) {
    ElMessage.error('WebSocket 未连接');
    return;
  }
  const gateway = gatewayList.value.find(g => g.id === selectedGatewayId.value);
  if (!gateway) {
    ElMessage.error('未选择有效的网关');
    return;
  }

  const commandToSend = {
    ...payload,
    gatewayId: gateway.ip
  };

  console.log('发送指令:', commandToSend);
  ws.sendMessage(JSON.stringify(commandToSend));
};

// 事件处理函数
const handleSearch = () => {
  // 实现搜索逻辑
  if (searchForm.deviceESN) {
    const filtered = deviceList.value.filter(device => 
      device.deviceESN?.includes(searchForm.deviceESN)
    );
    // 这里可以更新显示的设备列表
    ElMessage.info(`找到 ${filtered.length} 个匹配的设备`);
  }
};

const resetSearch = () => {
  searchForm.deviceESN = '';
};

const handleEsnInput = (value: string) => {
  searchForm.deviceESN = value.toUpperCase();
};

const handleAdd = () => {
  addForm.deviceId = null;
  addForm.deviceESN = '';
  addDialogVisible.value = true;
};

const handleRefresh = () => {
  sendCommand({ action: 'gateway', type: 'queryAll' });
};

const handleBatchDelete = async () => {
  if (selectedDevices.value.length === 0) {
    ElMessage.warning('请选择要删除的设备');
    return;
  }
  
  try {
    await ElMessageBox.confirm('确定要删除选中的设备吗？', '确认删除', {
      type: 'warning'
    });
    
    for (const device of selectedDevices.value) {
      sendCommand({ 
        action: 'gateway', 
        type: 'delete', 
        id: device.deviceId 
      });
    }
  } catch {
    // 用户取消删除
  }
};

const handleSelectionChange = (selection: any[]) => {
  selectedDevices.value = selection;
};

const handleView = (row: any) => {
  deviceForm.deviceId = row.deviceId;
  deviceForm.deviceESN = row.deviceESN;
  deviceForm.deviceStatus = row.deviceStatus;
  deviceType.value = '';
  
  // 查询设备类型
  sendCommand({ 
    action: 'gateway', 
    type: 'queryDeviceType', 
    id: row.deviceId 
  });
  
  dialogVisible.value = true;
};

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除设备 ${row.deviceId} 吗？`, '确认删除', {
      type: 'warning'
    });
    
    sendCommand({ 
      action: 'gateway', 
      type: 'delete', 
      id: row.deviceId 
    });
  } catch {
    // 用户取消删除
  }
};

const handleDropdownCommand = (command: string, row: any) => {
  switch (command) {
    case 'reboot':
      handleReboot(row);
      break;
    case 'version':
      handleQueryVersion(row);
      break;
    case 'gain':
      handleGainAdjust(row);
      break;
  }
};

const handleReboot = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要重启设备 ${row.deviceId} 吗？`, '确认重启', {
      type: 'warning'
    });
    
    sendCommand({ 
      action: 'gateway', 
      type: 'device_reboot', 
      id: row.deviceId 
    });
  } catch {
    // 用户取消重启
  }
};

const handleQueryVersion = (row: any) => {
  sendCommand({ 
    action: 'gateway', 
    type: 'queryVersion', 
    id: row.deviceId 
  });
};

const handleGainAdjust = (row: any) => {
  gainForm.deviceId = row.deviceId;
  gainForm.gain = null;
  queriedGain.value = '';
  gainDialogVisible.value = true;
};

const submitAdd = () => {
  addFormRef.value.validate((valid: boolean) => {
    if (valid) {
      sendCommand({ 
        action: 'gateway', 
        type: 'add', 
        id: addForm.deviceId,
        esn: addForm.deviceESN
      });
    }
  });
};

const cancelAdd = () => {
  addDialogVisible.value = false;
  addForm.deviceId = null;
  addForm.deviceESN = '';
};

const submitQueryGain = () => {
  sendCommand({ 
    action: 'gateway', 
    type: 'queryCircuitGain', 
    id: gainForm.deviceId 
  });
};

const submitSetGain = () => {
  if (!gainForm.gain) {
    ElMessage.error('请输入增益值');
    return;
  }
  
  sendCommand({ 
    action: 'gateway', 
    type: 'setCircuitGain', 
    id: gainForm.deviceId,
    gain: gainForm.gain
  });
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
};

const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
};
</script>

<style scoped lang="less">
.gateway-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.operation-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  
  .search-form {
    display: flex;
    align-items: center;
  }
  
  .action-buttons {
    display: flex;
    gap: 10px;
  }
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

:deep(.el-table) {
  --el-table-border-color: #dcdfe6;
  --el-table-header-bg-color: #f5f7fa;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
